var Q = require('q'),
    _ = require('lodash'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    ProduceWorkEnum = require('../../../ProduceWork/server/controllers/Enum.server.controller.js'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    workController = require('../../../CBO/server/controllers/Work.server.controller'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller'),
    itemMasterController = require('../../../CBO/server/controllers/ItemMaster.server.controller'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller'),
    wareHouseController = require('../../../CBO/server/controllers/WareHouse.server.controller'),
    extendEnumController = require('../../../Common/server/controllers/ExtendEnum.server.controller'),
    badTypeBindController = require('../../../QC/server/controllers/BadTypeBind.server.controller'),
    rcvRecordController = require('../../../ProduceWork/server/controllers/RcvRecord.server.controller');
//通过Barcode获取条码主档信息(打印)
exports.getBarcodeData = function (req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    barcodeMasterController.findBarcodeMaster(Barcode, function (err, result) {
        
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });
};
//通过Barcode获取条码主档信息(不良品检验)
exports.getBarcodeDataCheck = function (req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    barcodeMasterController.findBarcodeMasterBizRecordByBarcode(Barcode, function (err, result) {
        
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });
};

//通过物料id查找物料信息
exports.getItemCategory = function (req, res) {
    var parameter = req.body.Parameter,
        itemMasterId = parameter.ItemMasterId;
    itemMasterController.findItemCategoryById(itemMasterId, function (err, result) {
        
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询物料类别失败';
                newErr.message = '未找到对应的物料类别！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });
};

//根据code,获取枚举列表
exports.getExtendEnumByCode = function(req, res){
    var parameter = req.body.Parameter,
        code = parameter.code;
    extendEnumController.findByCode(code, function(err, data) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });   
        }
        else{
            res.json({
                Data: data.Options,
                Error: null
            });
        }
        
    });

}

//传入不良类型或不良位置的id，判断是哪类id
exports.getIdType = function(req, res){
    var parameter = req.body.Parameter,
        _id = parameter._id;
    extendEnumController.findByCode('BadType', function(err, data) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        for (var j = 0; j < data.Options.length; j++) {
            if (data.Options[j]._id == _id) {
                res.json({
                    Data: "BadType",
                    Error: null
                });
                return;
            }
        }
        if (j==data.Options.length){
            extendEnumController.findByCode('BadPosition', function(err, data) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                for (var i = 0; i < data.Options.length; i++) {
                    if (data.Options[i]._id == _id) {
                        res.json({
                            Data: "BadPosition",
                            Error: null
                        });
                        return;
                    }
                }
                if(i==data.Options.length){
                    res.json({
                        Data: "None",
                        Error: err
                    });
                }
            });
        }
               
    });

}

//不良品检验更新
//更新流水的采集时间、用户信息，删除原品质记录并重新创建。更新主档的用户
exports.updateBadData = function (req, res) {
    var parameter = req.body.Parameter,
        UserId = parameter.User,
        BarcodeId = parameter.BarcodeId,
        Barcode = parameter.Barcode,
        badRecords = parameter.badRecords,
        QCStatus = parameter.QCStatus,
        BizRecordId = parameter.BizRecord,
        workId = parameter.workId,
        one = parameter.one,
        departmentId = parameter.departmentId;
    var oldQCStatus = one.QCStatus,
        ReworkQty = one.ReworkQty,
        ItemMaster = one.ItemMaster;
    var dateNow = Date.now();
    var updatebizRecord = {
        Users: [UserId],
        CollectDateTime: dateNow,
        QCStatus: QCStatus,
        SysVersion: one.BizRecord.SysVersion
    };
    var operationRec;//存工序数据
    var transactions = [];//保存事务的
    //获取更新流水记录
    getUpdateBizRecord(BizRecordId, updatebizRecord, UserId);
    transactions.push({
        EntityName: 'BizRecord',
        Records: [updatebizRecord]
    }); 
    //获取删除qc的记录
    getDeleteQCRecord(BizRecordId).then(function (deleteQCRecords) {
        if(deleteQCRecords){
            transactions.push({
                EntityName: 'QCRecord',
                Records: deleteQCRecords
            });
        }
        //获取新增qc记录
        return addQCRecords(badRecords, UserId, BizRecordId)
    }).then(function(qcRecords) {    
        if (qcRecords) {
            transactions.push({
                EntityName: 'QCRecord',
                Records: qcRecords
            });
        }
        return queryOperation(ItemMaster, workId);
    }).then(function(operationRecord) {
        operationRec = operationRecord;
        var updateRecord = {
            Users: [UserId],
            QCStatus: QCStatus,
            SysVersion: one.SysVersion,
            RowStatus: BaseEnum.RowStatus.Modify.Value,
            CreatedBy: UserId,
            _id: BarcodeId,     
        };
        if(oldQCStatus!=QCEnum.QCStatus.Rework.Value&&QCStatus===QCEnum.QCStatus.Rework.Value){  
            updateRecord.QCReworkOperation = operationRecord._id;
            updateRecord.ReworkQty = ReworkQty ? ReworkQty+1 : 1;
        }
        transactions.push({
            EntityName: 'BarcodeMaster',
            Records: [updateRecord]
        });
        //增加入库信息,当前工序为入库工序并且质检状态必须是合格或让步时，进行入库操作
        if(operationRec.IsStoragePoint&&QCStatus===QCEnum.QCStatus.Concession.Value){
            return getAddRcvData(BizRecordId,one,userId,departmentId,operationRec._id);            
        }else{
            return Q.resolve();
        }
    }).then(function(rcvData) {
        if(rcvData){
            transactions.push({
                EntityName: 'RcvRecord',
                Records: [rcvData]
            });  
        }
        return Q.nfcall(Transaction.BatchSaveByTran, transactions);
    }).then(function() {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function(err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};


//通过Barcode获取检验作业条码主档信息
exports.getBarcodeDefectData = function (req, res) {
    var parameter = req.body.Parameter,
        BarcodeId = parameter.BarcodeId,
        Work = parameter.Work;

    // var returnData = [];
    var returnData = {
        bizRecordID:0,
        defectDatas:[]
    };
    
    barcodeMasterController.findBarcodeMasterByBarcodeMaster(BarcodeId, function(err,result){
       if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                returnData.bizRecordID = result.BizRecord;                                       
                
                qcRecordController.findAllQCRecords(result.BizRecord, function (err, results) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    }
                    else {
                        if (results == null) {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '查询品质记录失败';
                            newErr.message = '未找到对应的品质记录！';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                        }
                        else {
                            var BadTypeOptions = [];
                            var BadPositionOptions = [];
                            var qcRecords = results;

                            //查找所有的不良类型
                            enumController.findAllExtendEnum("BadType", function (err, result) {
                                if (err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                }
                                else {
                                    if (result == null) {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '查询不良类型失败';
                                        newErr.message = '未找到所有的不良类型！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                    else {
                                        BadTypeOptions = result.Options;
                                        //查找所有的不良类型
                                        enumController.findAllExtendEnum("BadPosition", function (err, result) {
                                            if (err) {
                                                res.json({
                                                    Data: null,
                                                    Error: err
                                                });
                                            }
                                            else {
                                                if (result == null) {
                                                    var newErr = new Error();
                                                    newErr.leval = 9;
                                                    newErr.title = '查询不良位置失败';
                                                    newErr.message = '未找到所有的不良位置！';
                                                    res.json({
                                                        Data: null,
                                                        Error: newErr
                                                    });
                                                }
                                                else {
                                                    BadPositionOptions = result.Options;
                                                    // var promises = [];
                                                    // results.forEach(function (result) {
                                                    //     promises.push(queryBadTypeAndBadPosition(result));   
                                                    // });
                                                    
                                                    qcRecords.forEach(function (qcRecord) {
                                                        for (var i = 0; i < BadTypeOptions.length; i++) {
                                                            if (BadTypeOptions[i].Value === qcRecord.BadType) {
                                                                for (var j = 0; j < BadPositionOptions.length; j++) {
                                                                    if (BadPositionOptions[j].Value === qcRecord.BadPosition) {

                                                                        returnData.defectDatas.push({
                                                                            BadType: BadTypeOptions[i].Name,
                                                                            BadTypeValue: BadTypeOptions[i].Value,
                                                                            BadPosition: BadPositionOptions[j].Name,
                                                                            BadPositionValue: BadPositionOptions[j].Value,
                                                                            Description: qcRecord.Description,
                                                                            Status:false,
                                                                            BizRecord: qcRecord.BizRecord
                                                                        })
                                                                    }
                                                                }
                                                                

                                                            }

                                                        }
                                                        
                                                    });
                                                    res.json({
                                                        Data: returnData,
                                                        Error: null
                                                    });

                                                }
                                            }

                                        });

                                    }
                                }

                            });


                        }
                    }

                });
            }
        }
    });

    
};


//不良品检验增加
exports.submitCheckWork = function (req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        Terminal = parameter.Terminal,
        TerminalName = parameter.TerminalName,
        Work = parameter.Work,
        WorkName = parameter.WorkName,
        WorkLocation = parameter.WorkLocation,
        WorkLocationName = parameter.WorkLocationName,
        userId = parameter.UserID,
        QCStatus = parameter.QCStatus,//0: 合格 1:不合格
        badRecords = parameter.badRecords,//不良信息记录
        one = parameter.one,
        departmentId = parameter.departmentId;
    //条码主档信息    
    var barcodeMaster = one._id,
        ItemMaster = one.ItemMaster,
        oldQCStatus = one.QCStatus,
        ReworkQty = one.ReworkQty;
    //bizRecord待入库的流水信息
    var dateNow = Date.now(),
        bizRecord = {
            CollectDateTime: dateNow,
            Users: [userId],
            QCType: 0,//质检类型：全检
            QCUser: userId,
            QCDateTime: dateNow,
            QCStatus: QCStatus,
            BarcodeMaster: barcodeMaster,
            Work: Work,
            WorkName: WorkName,
            WorkLocation: WorkLocation,
            WorkLocationName: WorkLocationName,
            Terminal: Terminal,
            TerminalName: TerminalName
        };
    var IsStoragePoint;//是否为入库点
    var transactions = [];//保存事务的
    var operRecord;
    //根据物料和作业查找工序
    queryOperation(ItemMaster, Work).then(function(operationRecord) {
        operRecord = operationRecord;
        IsStoragePoint = operationRecord.IsStoragePoint;        
        bizRecord.Operation = operationRecord._id;
        bizRecord.OperationName = operationRecord.Name;
        return queryBarcodeMaster(barcode);
    }).then(function(record) {
        var bindContext = {
            Work: Work,
            WorkName: WorkName,
            User: userId,
            WorkLocation: WorkLocation,
            WorkLocationName: WorkLocationName
        }
        //流水校验
        return barcodeMasterController.streamValidation(record, operRecord, bindContext);
    }).then(function(processException) {
        if (processException) {
            transactions.push(processException);
        }
        addBizRecord(bizRecord,userId); 
        transactions.push({
            EntityName: 'BizRecord',
            Records: [bizRecord]
        });
        //获取新增qc记录
        return addQCRecords(badRecords, userId, bizRecord._id);
    }).then(function(qcRecords) {
        if (qcRecords) {
            transactions.push({
                EntityName: 'QCRecord',
                Records: qcRecords
            });
        }
        //获取更新主档记录信息
        var updateRecord = updateBarcodeRecord(bizRecord,one,userId);
        transactions.push({
            EntityName: 'BarcodeMaster',
            Records: [updateRecord]
        });
        //增加入库信息,当前工序为入库工序并且质检状态必须是合格或让步时，进行入库操作
        if(IsStoragePoint&&bizRecord.QCStatus===QCEnum.QCStatus.Concession.Value){
            return getAddRcvData(bizRecord._id,one,userId,departmentId,operRecord._id);            
        }else{
            return Q.resolve();
        }
    }).then(function(rcvData) {
        if(rcvData){
            transactions.push({
                EntityName: 'RcvRecord',
                Records: [rcvData]
            });  
        }
        return Q.nfcall(Transaction.BatchSaveByTran, transactions);
    }).then(function() {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function(err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

//获取更新流水记录
function getUpdateBizRecord(BizRecordId, updatebizRecord, userId){
    updatebizRecord.RowStatus = BaseEnum.RowStatus.Modify.Value;
    updatebizRecord.CreatedBy = userId;
    updatebizRecord._id = BizRecordId;
}

//获取删除qc记录
function getDeleteQCRecord(BizRecordId){
    var deferred = Q.defer();
    var deleteQCRecords = [];
    qcRecordController.findAllQCRecords(BizRecordId, function(err, results) {
        if (err) {
            deferred.reject(err);
        }
        else{
            if (results) {
                _.forEach(results,function(result) {
                    deleteQCRecords.push({
                        RowStatus: BaseEnum.RowStatus.Delete.Value,
                        _id: result._id
                    });
                });
                deferred.resolve(deleteQCRecords);          
            }else{
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询数据错误';
                newErr.message = '没有找到对应流水的品质记录';
                deferred.reject(newErr);
            }
        }    
    });
    return deferred.promise;
}


//根据物料和作业查找工序
function queryOperation(itemMaster, work) {
    var deferred = Q.defer();

    if (!itemMaster) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.message = '主档未绑定物料';
        deferred.reject(newErr);
        return;
    }
    operationController.findByItemMasterAndWork(itemMaster, work, function(err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!result) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '非法数据';
            newErr.message = '没有找到对应的工序';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(result);
    });

    return deferred.promise;
}

function queryBarcodeMaster(barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (barcodeMaster == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '无法识别条码';
            newErr.message = '无法识别的条码，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(barcodeMaster);
    });

    return deferred.promise;
}

// 新增流水的记录
function addBizRecord(bizRecord,userId) {
    bizRecord._id = BaseFun.getObjectId();
    bizRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
    bizRecord.CreatedBy = userId;
}

// 新增品质记录的记录
function addQCRecords(badRecords,userId,bizRecordId) {
    var deferred = Q.defer();
    var qcRecords = [];
    _.forEach(badRecords, function(badRecord) {
        qcRecords.push({
            _id: BaseFun.getObjectId(),
            RowStatus: BaseEnum.RowStatus.Insert.Value,
            CreatedBy: userId,
            BizRecord: bizRecordId,
            QCNorm: 0,
            NormValue: '',
            BadType: badRecord.BadTypeValue,
            IsQualified: false,
            BadPosition: badRecord.BadPositionValue,
            Description: badRecord.Description
        }); 
    });  

    var promises = [];
    qcRecords.forEach(function (qcRecord) {
        promises.push(queryQCNorm(qcRecord));   
    });
    
    Q.all(promises).then(function () {
        deferred.resolve(qcRecords);
    }, function(err) {
        deferred.reject(err);
    });

    return deferred.promise;
}


function queryQCNorm (qcRecord) {
    var deferred = Q.defer();
    badTypeBindController.findQCNormIDByBadType(qcRecord.BadType, function (err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (result.QCNorm) {
            qcRecord.QCNorm = result.QCNorm._id;
        } 
        deferred.resolve();            
    });  
    return deferred.promise;
}
//获取更新的条码主档信息
function updateBarcodeRecord (bizRecord,barcodeRecord,userId) {
    var updateRecord = {
        SysVersion: barcodeRecord.SysVersion,
        RowStatus: BaseEnum.RowStatus.Modify.Value,
        CreatedBy: userId,
        _id: barcodeRecord._id,
        Users: bizRecord.Users,
        // BusinessStatus: bizRecord.BusinessStatus,
        QCStatus: bizRecord.QCStatus,
        BizRecord: bizRecord._id,
        Work: bizRecord.Work,
        WorkName: bizRecord.WorkName,
        WorkLocation: bizRecord.WorkLocation,
        WorkLocationName: bizRecord.WorkLocationName,
        Terminal: bizRecord.Terminal,
        TerminalName: bizRecord.TerminalName,
        Operation: bizRecord.Operation,
        OperationName: bizRecord.OperationName  
    };
    //原始qc状态不为返工&&新qc状态为返工
    if(barcodeRecord.QCStatus!=QCEnum.QCStatus.Rework.Value&&bizRecord.QCStatus===QCEnum.QCStatus.Rework.Value){
        updateRecord.QCReworkOperation = bizRecord.Operation;
        // updateRecord.ReworkQty = ReworkQty+1;
        updateRecord.ReworkQty = barcodeRecord.ReworkQty ? barcodeRecord.ReworkQty+1 : 1;
    }
    return updateRecord; 
}
//获取入库数据
function getAddRcvData(bizRecordId,barcodeRecord,userId,departmentId,operRecordId) {
    var deferred = Q.defer();
    var insertRcvData = {};
    wareHouseController.findByDepartmentDeep(departmentId).then(function(wareHouse) {
        var dateNow = Date.now();
        if (wareHouse) {
            insertRcvData = {
                _id: BaseFun.getObjectId(),
                RowStatus: BaseEnum.RowStatus.Insert.Value,
                CreatedBy: userId,
                BarcodeMaster: barcodeRecord._id,
                Barcode: barcodeRecord.Barcode,
                RcvBusinessType: 0,
                BusinessDocID: barcodeRecord.MO,
                ItemMaster: barcodeRecord.ItemMaster,
                RcvUser: userId,
                RcvDateTime: dateNow,
                RcvQty: 1,
                RcvOperation: operRecordId,
                BizRecord: bizRecordId,
                WareHouse: wareHouse._id
            }; 
            deferred.resolve(insertRcvData);      
        }
        else{
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询仓库错误';
            newErr.message = '未找到对应仓库！';
            deferred.reject(newErr);
        }
    },function(err) {
        deferred.reject(err);
    }); 

    return deferred.promise;
}

